package com.ruoyi.web.controller.master;

import java.io.IOException;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.master.domain.Club;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.master.service.IClubService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 社团Controller
 *
 * @author ruoyi
 * @date 2021-03-24
 */
@RestController
@RequestMapping("/master/club" )
public class ClubController extends BaseController {

    @Autowired
    private IClubService iClubService;

    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询社团列表
     */
    @PreAuthorize("@ss.hasPermi('master:club:list')")
    @GetMapping("/list")
    public TableDataInfo list(Club club) {
        startPage();
        List<Club> list = iClubService.queryList(club);
        list.forEach(club1 -> {
            club1.setSysUser(iSysUserService.selectUserById(club1.getUserId()));
        });
        return getDataTable(list);
    }

    /**
     * 获取社团详细信息
     */
    @PreAuthorize("@ss.hasPermi('master:club:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        Map<String, Object> result = new HashMap();
        Club club = iClubService.getById(id);
        result.put("club", club);
        List<SysUser> sysUsers = iSysUserService.selectUsersById(club.getUserId());
        result.put("clubAdminList", sysUsers);
        return AjaxResult.success(result);
    }

    /**
     * 新增社团
     */
    @PreAuthorize("@ss.hasPermi('master:club:add')" )
    @Log(title = "社团" , businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody Club club) {
        try {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(club.getUserId());
            sysUser.setIsClubAdmin(Constants.ISCLUBADMIN);
            iSysUserService.updateUser(sysUser);
            return toAjax(iClubService.save(club) ? 1 : 0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error();
        }
    }

    /**
     * 修改社团
     */
    @PreAuthorize("@ss.hasPermi('master:club:edit')" )
    @Log(title = "社团" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Club club) {
        return toAjax(iClubService.updateById(club) ? 1 : 0);
    }

    /**
     * 删除社团
     */
    @PreAuthorize("@ss.hasPermi('master:club:remove')" )
    @Log(title = "社团" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable Long[] ids) {
        try {
            List<Club> clubs = iClubService.listByIds(Arrays.asList(ids));
            int size = clubs.size();
            Long [] userIds = new Long[size];
            for (int i = 0; i < size; i++) {
                userIds[i] = clubs.get(i).getUserId();
            }
            iSysUserService.deleteUserByIds(userIds);
            return toAjax(iClubService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("删除异常");
        }
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}
